/**
 * Created by chocolate on 16/5/23.
 */

//引入系统模块
import React, {
  Component,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  TabBarIOS,
  ListView,
  SegmentedControlIOS,
} from 'react-native';

//引入TestData模块定义的测试数据变量,此处采用对象解构赋值
//TestData模块可以定义多种类型的测试数据;
var {leaveTestData} = require("./TestData");
var Title =require('./Title');
var query = require('./Query').query;

class LeaveList extends Component{

  /**
   * 构造函数
   * @param props
   */
  constructor(props){
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});  //数据源对象
    this.leaveList = [];  //从网络获取的所有孩子请假列表
    this.childList = this.props.childList;
    this.user = this.props.user;
    this.state = {
        dataSource:this.ds.cloneWithRows([]),
        selectedIndex:0,
        selectChild:0,                                      //当前选择的孩子ID
        //dataSource:this.ds.cloneWithRows(leaveTestData),    //当没有网络时,采用测试数据作为数据源
        childNames: [],        //SegmentedControlIOS的数据源
    }
  }

  /**
   * 组件加载成功回调函数。此处获取服务器请假数据并刷新请假列表
   */
  componentDidMount(){
    this._updateSegment();
    this._refreshLeaveInfo();
  }

  /**
   * 从childlist中提取childname列表,
   * 用于更新SegmentedControlIOS
   */
  _updateSegment(){
    var childNameList = [];
    this.childList.forEach((item, index, array) =>{
      childNameList.push(item.name);
    })
    this.setState({childNames:childNameList});
    console.log("开始给Segment加载孩子姓名列表"+this.state.childNames);

    if(this.childList.length == 0){return;}
  }

  /**
   * 获取并刷新请假申请列表
   * @private
   */
  _refreshLeaveInfo(){
    this.leaveList = [];
    query.getLeaveApplies(this.user.phone,this,function(owner,response){
      if(response.success === true){
        owner.leaveList = response.message;
        owner._updateLeaveList();}})
  }

  /**
   * 更新本地请假列表数据源
   * @private
   */
  _updateLeaveList(){
    this.setState({dataSource:this.ds.cloneWithRows(this.leaveList)});
  }

  /**
   * 单击list-item的相应事件,此处弹出的页面待定。也许是撤回请假申请
   * @private
   */
  _onPressRow(){

  }

  /**
   * 渲染list-view的行
   * @param rowData
   * @param sectionID
   * @param rowID
   * @private
   */
  _renderRow(rowData: string,sectionID: number, rowID: number){
    return(
      <View style={styles.listRow}>
        <Text style={styles.leaveTitle}>{rowData.studentName}的{rowData.reason}申请</Text>
        <Text style={styles.leaveContent}>请假时间:{rowData.startTime} - {rowData.endTime}</Text>
        <Text style={styles.leaveContent}>请假事由:{rowData.detail}</Text>
        <Text style={styles.leaveContent}>提交时间:{rowData.applyTime}</Text>
        <Text style={styles.leaveContent}>审批人:{rowData.teacherPhone}</Text>
      </View>
    )
  }

  /**
   * 点击返回按钮,返回上层界面
   * @private
   */
  _onPressReturn(){
    this.props.navigator.pop();
  }

  /**
   * 点击"申请"按钮,进入请假申请页面
   * @private
   */
  _onPressApplyLeave(){
    this.props.navigator.push({name:"LeaveScreen",params:{parent:this.user,child:this.childList[this.state.selectedIndex]}});
  }

  /**
   * 点击segment后触发此事件,
   * 切换当前孩子的状态视图
   */
  _onSegmentChange(event) {
    this.setState({selectedIndex: event.nativeEvent.selectedSegmentIndex,});
    var eventList = [];
    this.leaveList.forEach((item, index, array) =>{
                        if(this.state.childNames[this.state.selectedIndex] === item.studentName){
                          eventList.push(item);
                        }
                      });
    this.setState({dataSource:this.ds.cloneWithRows(eventList)});
  }

  _onValueChange(value) {
    console.log("切换Segment,当前所选择的孩子为:"+value);
  }

  /**
   * 渲染整体页面
   * @returns {XML}
   */
  render(){
    return(
      <View style={styles.container}>
        <Title title={{left:"返回",center:"请假申请列表",right:"申请",
              leftAct:this._onPressReturn.bind(this),rightAct:this._onPressApplyLeave.bind(this)}}></Title>

        <View style={styles.segmentContainer}>
          <SegmentedControlIOS
            style={styles.segment}
            tintColor='#06a9fe'
            values={this.state.childNames}
            selectedIndex={this.state.selectedIndex}
            onChange={this._onSegmentChange.bind(this)}
            onValueChange={this._onValueChange.bind(this)} />
         </View>   

        <ListView dataSource={this.state.dataSource}
                  renderRow={this._renderRow.bind(this)}
                  enableEmptySections={true}
                  style={styles.listView} />

      </View>
    )

  }
}

/**
 * 定义本模块的样式表
 * @type {*|{type, property}|{panHandlers}|Object|{duration, create, update}|Config}
 */
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#eeeeee',
    flex: 1,
  },
  listView: {
    
  },
  listRow:{
    alignSelf:'stretch',
    flex: 1,
    height:150,
    justifyContent: 'center',
    backgroundColor: '#fff',
    padding: 10,
    marginVertical: 5,
  },
  leaveTitle:{
    fontSize:18,
    color:'#2981b1',
    marginLeft:10,
    marginTop:12,
    marginBottom:12,
  },
  leaveContent:{
    fontSize:16,
    color:'#7d7d7d',
    marginLeft:10,
    marginBottom:8,
  },
  segment:{
    flex:1,
    marginTop:10,
    marginBottom:10,
    marginLeft:20,
    marginRight:20,
  },
  segmentContainer:{
    justifyContent:'center',
    height:50,
  },
})

/**
 * 导出请假申请列表模块
 * @type {LeaveList}
 */
module.exports = LeaveList;
